﻿using System;
using System.Web;
using System.Web.UI.WebControls;

namespace IIOS.SP.WebParts.Navigation.WebAppNavigator
{
    // Borrowed from http://sharepoint-tweaking.blogspot.com.au/2008/01/treeview-with-select-onclick-event.html
    // Thanks Per Gårdebrink
    class GTreeView : System.Web.UI.WebControls.TreeView
    {
        private static readonly object TreeViewSelected = new object();

        public event EventHandler Select
        {
            add { base.Events.AddHandler(TreeViewSelected, value); }
            remove { base.Events.RemoveHandler(TreeViewSelected, value); }
        }

        protected virtual void OnSelect(EventArgs e)
        {
            EventHandler handler = (EventHandler)base.Events[TreeViewSelected];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        internal void RaiseOnSelect()
        {
            this.OnSelect(EventArgs.Empty);
        }

        protected override void RaisePostBackEvent(string eventArgument)
        {
            base.RaisePostBackEvent(eventArgument);
            if (eventArgument.Length != 0)
            {
                char ch = eventArgument[0];
                string val = HttpUtility.HtmlDecode(eventArgument.Substring(1));
                // Pathseparator in eventArgument is backslash, so we must temporary set the separator
                char oldPathSeparator = PathSeparator;
                PathSeparator = '\\';
                TreeNode node = FindNode(val);
                PathSeparator = oldPathSeparator;

                if (ch == 's')
                {
                    if (node != null)
                    {
                        if ((node.SelectAction == TreeNodeSelectAction.Select) || (node.SelectAction == TreeNodeSelectAction.SelectExpand))
                        {
                            RaiseOnSelect();
                        }
                    }
                }
            }
        }
    }
}
